package cn.test.controller;

import cn.test.entity.User;
import cn.test.service.AppException;
import cn.test.service.LoginService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.sql.Date;
import java.util.List;

/**
 * Created by sam on 2017/11/23.
 */
@Controller
public class LoginController {
    @ExceptionHandler
    public String handleEX(Exception e, HttpServletRequest request) {
        System.out.println("handleEx()");
        //应用异常,需要明确提示用户采取正确的操作
        if (e instanceof AppException) {
            request.setAttribute("login_failed", e.getMessage());
            return "login";
        }
        //其他异常
        return "error";
    }

    @Resource(name = "loginService")
    private LoginService loginService;

    @RequestMapping("/login.do")
    public String login(HttpServletRequest request, HttpSession httpsession) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println("username:" + username + " password:" + password);
        User user = loginService.checkLogin(username, password);
        httpsession.setAttribute("user", user);
        return "redirect:/user.do";
    }

    @RequestMapping("/user.do")
    public String user(HttpServletRequest request) {
        try {
            List<User> users = loginService.findbyAll();
            request.setAttribute("users", users);
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }

        return "user";
    }

    @RequestMapping("/load.do")
    public String load(HttpServletRequest request) {
        String id = request.getParameter("id");
        User user = loginService.findById(id);
        request.setAttribute("user", user);
        return "userUpdate";
    }

    @RequestMapping("/update.do")
    public String update(HttpServletRequest request) {
        String name = request.getParameter("name");
        System.out.println("修改传递过来的值"+name);
        Date birthday = Date.valueOf(request.getParameter("birthday"));
        System.out.println("修改传递过来的值"+birthday);
        String id = request.getParameter("id");
        System.out.println("修改传递过来的值"+id);
        User user = loginService.findById(id);
        user.setBirthday(birthday);
        user.setName(name);
        loginService.updateById(user);
        return "redirect:/user.do";
    }
}

